﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using DataInfo;
using KenLib.BusinessManager;

public partial class JOINT_frmJ_StaffWorkedCompInput : System.Web.UI.Page
{
    protected void Page_PreRender(object sender, EventArgs e)
    {
        ViewState["CountingSubmitJS56"] = Session["CountingSubmitJS56"];
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        ((JOINT_MstPage_JOINT)this.Master).changeTitle("会社履歴情報登録");
        ((JOINT_MstPage_JOINT)this.Master).HideLiArea("frmJ_StaffWorkedCompInput");
        //AppCode_Common.ShowEmtyGrid<本社履歴>(grv, 4, "データがありません。", "");

        //Session["IdEmp"] = 100;
        if (!IsPostBack)
        {
            Session["CountingSubmitJS56"] = Server.UrlEncode(System.DateTime.Now.ToString());
            ViewState["indexPage"] = 0;
            ViewState["IdCurrent"] = "";
            ViewState["TableTempJS56Insert"] = null;
            txt_会社名.Focus();
            if (Request.QueryString["id"] != null)
            {
                int id;
                Int32.TryParse(Request.QueryString["id"].ToString(), out id);
                LoadMessage();
                LoadDataGrvForUpdate(id.ToString());
                grv.Visible = true;
                btn_次.Enabled = false;
                Session["modeStaffWorkedCompInput"] = "2";

                string ngaysinh = new 基本情報Manager().getNgaySinh(Int32.Parse(Session["IdEmp"].ToString()));
                if (ngaysinh.Length >= 10)
                    hfNgaySinh.Value = ngaysinh.Substring(0, 10);
            }
            else
            {
                LoadDataGridView();
                LoadMessage();
                Session["modeStaffWorkedCompInput"] = "1";
                if (Session["IdEmp"] != null && Session["IdEmp"] != "")
                {
                    string ngaysinh = new 基本情報Manager().getNgaySinh(Int32.Parse(Session["IdEmp"].ToString()));
                    if (ngaysinh.Length >= 10)
                        hfNgaySinh.Value = ngaysinh.Substring(0, 10);
                }
            }
        }
    }
    
    /// <summary>
    /// Load thong diep loi vao cac control valid
    /// </summary>
    private void LoadMessage()
    {
        this.RequiredFieldValidator1.ErrorMessage =  GetError("ER00001");
        this.RequiredFieldValidator2.ErrorMessage =  GetError("ER00001");
        this.RequiredFieldValidator3.ErrorMessage =  GetError("ER00001");
        this.RequiredFieldValidator4.ErrorMessage =  GetError("ER00001");
        this.CustomValidator2.ErrorMessage =  GetError("ER00001");
        this.CustomValidator3.ErrorMessage =  GetError("ER00001");
        this.RegularExpressionValidator1.ErrorMessage =  GetError("ER00002");
        this.RegularExpressionValidator2.ErrorMessage =  GetError("ER00002");
        CustomValidator1.ErrorMessage = GetError("ER00005");
        CustomValidator4.ErrorMessage = GetError("ER00005");
        CustomValidator6.ErrorMessage = GetError("ER00005");
    }

    protected void btn_戻る_Click(object sender, EventArgs e)
    {
        if (Session["modeStaffWorkedCompInput"].ToString() == "1")
            Response.Redirect("frmJ_StaffAcademicInput.aspx");
        else
            Response.Redirect("frmJ_EmpBasicInfo.aspx");
    }
    protected void btn_次_Click(object sender, EventArgs e)
    {
        if (Session["modeStaffWorkedCompInput"].ToString() == "1")
            Response.Redirect("frmJ_StaffImmiHistoryInput.aspx");
    }
    protected void btn_リセット_Click(object sender, EventArgs e)
    {
        ClearTextPage();
        if (Session["modeStaffWorkedCompInput"] != null)
        {
            if (Session["modeStaffWorkedCompInput"] == "2")
            {
                
            }

            if (Session["modeStaffWorkedCompInput"] == "1")
            {
                string strIdCurrent = ViewState["IdCurrent"] != null ? ViewState["IdCurrent"].ToString() : "";
                if (strIdCurrent != "")
                {
                    DataTable dt = (DataTable)ViewState["会社履歴情報TableJS56"];
                    int index = Int32.Parse(ViewState["indexJS56"].ToString());

                    txt_会社名.Text = dt.Rows[index]["会社名"].ToString();
                    txt_部門名.Text = dt.Rows[index]["部門名"].ToString();
                    txt_仕事内容.Text = dt.Rows[index]["仕事内容"].ToString();
                    txt_主な実績.Text = dt.Rows[index]["主な実績"].ToString();
                    txt_開始年月日.Text = dt.Rows[index]["開始年月日"].ToString() != "" ? dt.Rows[index]["開始年月日"].ToString().Substring(0, 10) : "";
                    txt_終了年月日.Text = dt.Rows[index]["終了年月日"].ToString() != "" ? dt.Rows[index]["終了年月日"].ToString().Substring(0, 10) : "";

                    string temp = dt.Rows[index]["企業分類コード"].ToString();
                    if (temp != "")
                    {
                        ListItem lst = ddl_企業分類コード.Items.FindByValue(temp);
                        ddl_企業分類コード.SelectedIndex = ddl_企業分類コード.Items.IndexOf(lst);

                    }
                    LoadDataGridView();
                }
            }
        }
    }

    /// <summary>
    /// Xoa sach text
    /// </summary>
    private void ClearTextPage()
    {
        txt_会社名.Text = "";
        txt_部門名.Text = "";
        txt_仕事内容.Text = "";
        txt_主な実績.Text = "";
        txt_開始年月日.Text = "";
        txt_終了年月日.Text = "";
        ddl_企業分類コード.SelectedIndex = 0;
        txt_会社名.Focus();
    }
    
    protected void btn_登録_Click(object sender, EventArgs e)
    {
        if (Session["CountingSubmitJS56"].ToString() == ViewState["CountingSubmitJS56"].ToString())
        {
            会社履歴情報 obj = new 会社履歴情報();

            obj.廃止区分 = 0;
            obj.会社名 = ConvertHTMLtoText(txt_会社名.Text.Trim().ToString());
            obj.部門名 = ConvertHTMLtoText(txt_部門名.Text.Trim().ToString());
            obj.仕事内容 = ConvertHTMLtoText(txt_仕事内容.Text.Trim().ToString());
            obj.主な実績 = ConvertHTMLtoText(txt_主な実績.Text.Trim().ToString());

            DateTime d1 = DateTime.Parse(txt_開始年月日.Text);
            obj.開始年月日 = d1;

            DateTime d2 = DateTime.Parse(txt_終了年月日.Text);
            obj.終了年月日 = d2;
            obj.企業分類コード = Int32.Parse(ddl_企業分類コード.SelectedValue.ToString());

            int kq;

            //////////////////////////////////////////////////////////////////////////////////////////
            //-----------------------------Mode Insert-----------------------------------------------
            /////////////////////////////////////////////////////////////////////////////////////////

            if (Session["modeStaffWorkedCompInput"].ToString() == "1")//Insert
            {
                obj.社員ID = Int32.Parse(Session["IdEmp"].ToString());
                
                string ID = ViewState["IdCurrent"].ToString();
                if (ID != "")//Update of insert
                {
                    obj.ID = Int32.Parse(ID);
                    bool checkHasChanged = false;
                    checkHasChanged = new 会社履歴情報Manager().checkHasChangedIn会社履歴情報UpdateCurrent(obj);
                 
                    if (checkHasChanged == false)
                    {
                        //Update information again.
                        kq = new 会社履歴情報Manager().update_ModeInsert_js56_Vh(obj);
                        if (kq != 0)
                        {
                            Session["CountingSubmitJS56"] = Server.UrlEncode(System.DateTime.Now.ToString());
                            ClearTextPage();
                            LoadDataGridView();
                            btn_登録.Text = "登録";
                            ViewState["IdCurrent"] = "";
                            ViewState["IdCurrent_JS_56_After"] = ID;
                        }
                    }
                    else
                    { 
                        // check having a exists duplicate
                        bool check_exits = false;
                        check_exits = new 会社履歴情報Manager().checkExistIn会社履歴情報InsertMode(obj);
                        if (check_exits == true)
                        {
                            // Has a duplicate
                            // show alert
                            string MessageCode = GetError("ER00009");
                            Page.ClientScript.RegisterStartupScript(typeof(Page), "Same 01", "alert('" + MessageCode + "');", true);
                        }
                        else
                        {
                            //Update information has changed
                            kq = new 会社履歴情報Manager().update_ModeInsert_js56_Vh(obj);
                            if (kq != 0)
                            {
                                Session["CountingSubmitJS56"] = Server.UrlEncode(System.DateTime.Now.ToString());
                                ClearTextPage();
                                LoadDataGridView();
                                btn_登録.Text = "登録";
                                ViewState["IdCurrent"] = "";
                                ViewState["IdCurrent_JS_56_After"] = ID;
                            }
                        }

                    }
                }
                else//Insert of Insert
                {
                    // check exists a duplicate 
                    // before new insert

                    bool check_exists = false;
                    check_exists = new 会社履歴情報Manager().checkExistIn会社履歴情報InsertMode(obj);
                    if (check_exists == true)
                    {
                        // Had a duplicate. Not Valid
                        // show alert
                        string MessageCode = GetError("ER00009");
                        Page.ClientScript.RegisterStartupScript(typeof(Page), "Same 01", "alert('" + MessageCode + "');", true);
                    }
                    else
                    {
                        int IdOutput;
                        kq = new 会社履歴情報Manager().InsertPartialTable(obj, out IdOutput);
                        if (kq != 0 && IdOutput != 0)
                        {
                            Session["CountingSubmitJS56"] = Server.UrlEncode(System.DateTime.Now.ToString());
                            ClearTextPage();
                            ViewState["IdCurrent_JS_56_Output"] = IdOutput.ToString();
                            LoadDataGridView();
                        }
                    }
                }
            }
            else if (Session["modeStaffWorkedCompInput"].ToString() == "2")//Update
            {
                //-----------------------------------Mode Update--------------------------
                string Id = Request.QueryString["id"].ToString();
                obj.ID = Int32.Parse(Id);
                kq = new 会社履歴情報Manager().update_ModeInsert_js56_Vh(obj);
                if (kq != 0)
                {
                    ClearTextPage();
                    Session["CountingSubmitJS56"] = Server.UrlEncode(System.DateTime.Now.ToString());
                    Response.Redirect("frmJ_EmpBasicInfo.aspx");
                }
            }
        }
        else
        {
            ClearTextPage();
            LoadDataGridView();
        }
    }

    /// <summary>
    /// Lay thong diep loi ung voi ma loi
    /// </summary>
    /// <param name="p"></param>
    /// <returns></returns>
    private string GetError(string p)
    {
        Error er = new Error();
        er.ErrorID = p;
        ErrorManager frm_error = new ErrorManager();
        DataTable dt = frm_error.getError(er);
        return dt.Rows[0][2].ToString();
    }

    /// <summary>
    /// Do du lieu vao GridView
    /// </summary>
    private void LoadDataGridView()
    {
        String id = Session["IdEmp"].ToString();
        DataTable lst = new 会社履歴情報Manager().SelectPartial(id);
        if (lst.Rows.Count > 0)
        {
            grv.DataSource = lst;
            grv.DataBind();
            ViewState["TableTempJS56Insert"] = lst;
        }
        else
        {
            string Header = "ID,会社名,部門名,開始年月日,終了年月日";
            ShowGridViewNotClassEmpty(grv, Header, "データーがありません。");
        }

    }
    
    /// <summary>
    /// Xu ly load du lieu cho GridView khi phan trang
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void grv_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        int index = e.NewPageIndex;
        ViewState["indexPage"] = index;

        grv.PageIndex = index;
        LoadDataGridView();
    }
    
    protected void grv_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Attributes["onmouseover"] = "this.style.cursor='hand';this.style.textDecoration='none';";
            e.Row.Attributes.Add("onclick", "javascript:__doPostBack('ctl00$ContentPlaceHolder1$grv','Load$" + e.Row.RowIndex + "')");
        }

    }

    protected void grv_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("Load"))
        {
            int pagecurrent = Int32.Parse(ViewState["indexPage"].ToString());
            int index;
            if (pagecurrent == 0)
                index = Int32.Parse(e.CommandArgument.ToString());
            else
                index = Convert.ToInt32(e.CommandArgument) + pagecurrent * 10;
            if (index == -1) return;

            string mode = Session["modeStaffWorkedCompInput"] != null ? Session["modeStaffWorkedCompInput"].ToString() : "";
            if (mode == "1")
            {
                DataTable dt = null;
                //dt = new 会社履歴情報Manager().SelectPartial(Session["IdEmp"].ToString());
                dt = (DataTable)ViewState["TableTempJS56Insert"];
                if (dt != null && dt.Rows.Count > 0)
                {
                    txt_会社名.Text = dt.Rows[index]["会社名"].ToString();
                    txt_部門名.Text = dt.Rows[index]["部門名"].ToString();
                    txt_仕事内容.Text = dt.Rows[index]["仕事内容"].ToString();
                    txt_主な実績.Text = dt.Rows[index]["主な実績"].ToString();
                    txt_開始年月日.Text = dt.Rows[index]["開始年月日"].ToString() != "" ? dt.Rows[index]["開始年月日"].ToString().Substring(0, 10) : "";
                    txt_終了年月日.Text = dt.Rows[index]["終了年月日"].ToString() != "" ? dt.Rows[index]["終了年月日"].ToString().Substring(0, 10) : "";

                    string temp = dt.Rows[index]["企業分類コード"].ToString();
                    if (temp != "")
                    {
                        ListItem lst = ddl_企業分類コード.Items.FindByValue(temp);
                        ddl_企業分類コード.SelectedIndex = ddl_企業分類コード.Items.IndexOf(lst);

                    }
                    ViewState["IdCurrent"] = dt.Rows[index]["ID"].ToString();
                    btn_登録.Text = "更新";
                    ViewState["会社履歴情報TableJS56"] = dt;
                    ViewState["indexJS56"] = index;
                }
            }
        }
    }
 
    /// <summary>
    /// Do du lieu vao gridview mode: Update
    /// </summary>
    /// <param name="Id"></param>
    private void LoadDataGrvForUpdate(String Id)
    {
        DataTable dt = null;
        dt = new 会社履歴情報Manager().sp_SelectModeUpdate_js56_Hoat(Id);
        if (dt.Rows.Count > 0)
        {
            int index = dt.Rows.Count - 1;

            txt_会社名.Text = dt.Rows[index]["会社名"].ToString();
            txt_部門名.Text = dt.Rows[index]["部門名"].ToString();
            txt_仕事内容.Text = dt.Rows[index]["仕事内容"].ToString();
            txt_主な実績.Text = dt.Rows[index]["主な実績"].ToString();
            txt_開始年月日.Text = dt.Rows[index]["開始年月日"].ToString();
            txt_終了年月日.Text = dt.Rows[index]["終了年月日"].ToString();

            string temp = dt.Rows[index]["企業分類コード"].ToString();
            if (temp != "")
            {
                ListItem lst = ddl_企業分類コード.Items.FindByValue(temp);
                ddl_企業分類コード.SelectedIndex = ddl_企業分類コード.Items.IndexOf(lst);

            }
        }
    }

    /// <summary>
    /// chuyen tu chuoi van ban sang ma HTML
    /// </summary>
    /// <param name="temp"></param>
    /// <returns></returns>
    public string ConvertTexttoHTML(string temp)
    {
        temp = temp.Replace("<", "&lt;");
        temp = temp.Replace(">", "&gt;");
        return temp;
    }

    /// <summary>
    /// chuyen tu ma HTML sang van ban
    /// </summary>
    /// <param name="temp"></param>
    /// <returns></returns>
    public string ConvertHTMLtoText(string temp)
    {
        temp = temp.Replace("&lt;", "<");
        temp = temp.Replace("&gt;", ">");
        temp = temp.Replace(Convert.ToString((char)13), "<br/>");
        return temp;
    }

    protected void grv_PreRender(object sender, EventArgs e)
    {
        //Highlight when has a Update state of Insert Mode 
        if (ViewState["IdCurrent_JS_56_After"] != null && ViewState["IdCurrent_JS_56_After"] != "")
        {
            if (string.IsNullOrEmpty(ViewState["IdCurrent_JS_56_After"].ToString()))
            {
                return;
            }
            for (int i = 0; i < grv.Rows.Count; i++)
            {
                string IdKey = grv.DataKeys[i].Value.ToString();
                if (IdKey == ViewState["IdCurrent_JS_56_After"].ToString())
                {
                    grv.Rows[i].CssClass = "update";
                    ViewState["IdCurrent_JS_56_After"] = "";
                }
            }
        }

        //Highlight when has a state insert new
        if (ViewState["IdCurrent_JS_56_Output"] != null && ViewState["IdCurrent_JS_56_Output"] != "")
        {
            if (string.IsNullOrEmpty(ViewState["IdCurrent_JS_56_Output"].ToString()))
            {
                return;
            }
            for (int i = 0; i < grv.Rows.Count; i++)
            {
                string IdKey = grv.DataKeys[i].Value.ToString();
                if (IdKey == ViewState["IdCurrent_JS_56_Output"].ToString())
                {
                    grv.Rows[i].CssClass = "insert";
                    ViewState["IdCurrent_JS_56_Output"] = "";
                }
            }
        }


    }

    /// <summary>
    /// Hien thi du lieu rong cho Gridview
    /// </summary>
    /// <param name="grv"></param>
    /// <param name="strTableHeader"></param>
    /// <param name="strEmpty"></param>
    public void ShowGridViewNotClassEmpty(GridView grv, string strTableHeader, string strEmpty)
    {
        DataTable dt = new DataTable();
        string[] arrColumnNames = strTableHeader.Split(',');
        foreach (string str in arrColumnNames)
        {
            dt.Columns.Add(str);
        }
        grv.ShowFooter = false;
        DataRow r = dt.NewRow();
        dt.Rows.InsertAt(r, 0);
        grv.DataSource = dt;
        grv.DataBind();
        grv.Rows[0].Cells.Clear();
        TableCell cell = new TableCell();
        cell.ColumnSpan = grv.Columns.Count + 1;
        cell.Text = strEmpty;
        grv.Rows[0].Cells.Add(cell);

    }

    /// <summary>
    /// Coder: Ha Van Hoat
    /// Function: Xu ly hien thi chuoi dai len GridView
    /// </summary>
    public string ShowTextLength(object str)
    {
        if (str == null || str.ToString() == "")
            return "";
        string temp = str.ToString();
        if (checkContainsUnicodeCharacter(temp))
        {
            //true tieng nhat
            if (temp.Length > 10)
            {
                temp = temp.Substring(0, 10) + "...";
            }
        }
        else
        {
            //tieng viet
            if (temp.Length > 20)
            {
                temp = temp.Substring(0, 20) + "...";
            }
        }

        return temp;
    }

    /// <summary>
    /// Coder: Ha Van Hoat
    /// Function: Kiem tra chuoi dau vao co thuoc bang ma Unicode
    /// </summary>
    public bool checkContainsUnicodeCharacter(string input)
    {
        const int MaxAnsiCode = 255;
        char[] a = input.ToCharArray();
        for (int i = 0; i < a.Length; i++)
        {
            if (a[i] > MaxAnsiCode)
            {
                return true;
            }
        }
        return false;
    }
}
